package com.github.bridge.component;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import com.github.bridge.domain.SysLog;
import com.github.bridge.request.BaseDTO;
import com.github.bridge.service.SysLogService;
import com.github.bridge.util.Const;
import com.github.bridge.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import wiki.xsx.core.log.Log;
import wiki.xsx.core.log.LogCallback;
import wiki.xsx.core.support.MethodInfo;

import java.lang.annotation.Annotation;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class LogCallBack implements LogCallback {
    private final SysLogService sysLogService;
//    private final ThreadPoolExecutor customExecutor1;

    public void callback(Annotation annotation, MethodInfo methodInfo, Map<String, Object> paramMap, Object result) {
        ThreadUtil.execAsync(() -> {
            saveLog(annotation, methodInfo, paramMap, result);
        }, false);
    }

    public void saveLog(Annotation annotation, MethodInfo methodInfo, Map<String, Object> paramMap, Object result) {
        SysLog sysLog = new SysLog();
        Object object = paramMap.get("dto");
        if (ObjUtil.isNull(object)) {
            object = BeanUtil.toBean(paramMap, Map.class);
        }
        BaseDTO baseDTO = BeanUtil.toBean(object, BaseDTO.class);
        sysLog.setSystemId(baseDTO.getSystemId());
        if (annotation instanceof Log) {
            Log log = (Log) annotation;
            String value = log.value();
            sysLog.setAction(value);
        }
        sysLog.setRequestParam(JSONUtil.toJsonStr(object));
        if (ObjUtil.isNull(result)) {
            sysLog.setSuccess(Const.NO);
        } else {
            sysLog.setSuccess(Const.YES);
            R bean = JSONUtil.toBean(JSONUtil.toJsonStr(result), R.class);
            Object data = bean.getData();
            Map map = JSONUtil.toBean(JSONUtil.toJsonStr(data), Map.class);
            sysLog.setResponseParam(JSONUtil.toJsonStr(data));
            try {
                String provider = map.get("provider").toString();
                sysLog.setProvider(provider);
            } catch (Exception e) {
                log.error("没有解析到服务商", e);

                throw new RuntimeException("没有解析到服务商");
            }

        }

        sysLog.setTime(methodInfo.getTakeTime());
        sysLogService.save(sysLog);
    }
}
